import { fileURLToPath } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { join } from 'node:path'
import { writeFileSync } from 'node:fs'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode })=> {
  // 改成 function 形式
  console.log('----[vite.config.js]---', command, mode, process.env.NODE_ENV)

  // 环境判断
  const isDev = process.env.NODE_ENV === 'development'
  const isProd = process.env.NODE_ENV === 'production'

  const base = !isDev
    ? isProd
      ? 'http://生产地址'
      : 'http://dev/qa-地址'
    : '/child/vite/';
  return {
    base,
    plugins: [
      vue(),
      vueJsx(),
      (function() {
        let basePath = ''
        return {
          name: 'vite:micro-app',
          apply: 'build',
          configResolved(config) {
            console.log('----[my plugin]----', config.base, config.build.assetsDir)
            basePath = `${config.base}${config.build.assetsDir}/`
          },
          writeBundle(options, bundle) {
            for(const chunkName in bundle) {
              if (Object.prototype.hasOwnProperty.call(bundle, chunkName)) {
                const chunk = bundle[chunkName]
                if (chunk.fileName && chunk.fileName.endsWith('.js')) {
                  chunk.code = chunk.code.replace(/(from|import\()(\s*['"])(\.\.?\/)/g, (all, $1, $2, $3) => {
                    console.log('---[plugin write]---', $3, basePath)
                    return all.replace($3, new URL($3, basePath))
                  })
                  const fullPath = join(options.dir, chunk.fileName)
                  writeFileSync(fullPath, chunk.code)
                }
              }
            }
          }
        }
      })()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    // 默认是启用的
    server: {
      cors: true,
    }
  }
})
